<template>
  <view class="bg-gray-50 min-h-screen w-[750rpx] pb-[150rpx] box-border">
    <!-- 用户信息头部 -->
    <view class="bg-gradient-to-r from-blue-600 to-blue-800 text-white p-[40rpx] rounded-b-[40rpx] shadow-lg">
      <view class="flex justify-between items-center mb-[30rpx]">
        <view class="flex items-center text-[28rpx]">
          <!-- <IconFont name="location" class="mr-[10rpx]" /> -->
          <text class="mr-4" v-if="locationObj.address_component?.city">{{ locationObj.address_component?.city }}</text>
          <text class="text-[24rpx] opacity-80"> V1.0.0 {{ publicTime }} </text>
        </view>
        <view @tap="handleSetting" class="w-[60rpx] h-[60rpx] bg-white bg-opacity-20 rounded-full flex items-center justify-center">
          <!-- <IconFont name="tuichu" class="text-[30rpx]" /> -->
          <IconFont font-class-name="iconfont" class-prefix="icon" name="tuichu" size="20" color="#fff" />
        </view>
      </view>

      <view class="flex items-center mb-[30rpx]">
        <view class="w-[120rpx] h-[120rpx] rounded-full border-4 border-white border-opacity-30 bg-white overflow-hidden mr-[30rpx]" @tap="goinfo()">
          <image :src="getFullPath(userInfo.avatar_url)" class="w-full h-full object-cover" @error="handleAvatarError" />
        </view>
        <view class="flex-1">
          <view class="text-[40rpx] font-bold mb-[10rpx] flex items-center">
            <view class="max-w-300rpx truncate">{{ userInfo.name }}</view>
            <view
              v-if="userInfo.user_type == '3' || userInfo.vip == 1"
              class="bg-gradient-to-r scale-[0.7] from-yellow-400 to-yellow-600 text-yellow-800 px-[15rpx] py-[5rpx] rounded-[20rpx] text-[24rpx] font-bold ml-[15rpx]"
            >
              {{ userInfo.vip == 1 ? "SVIP会员" : "普通会员" }}
            </view>
          </view>
          <text class="text-[28rpx] flex items-center opacity-90">
            平台ID:
            <text class="bg-white ml-1 bg-opacity-20 px-[15rpx] py-[3rpx] rounded-[15rpx] text-[24rpx]">{{ userInfo.id ? userInfo.id : "888888" }}</text>
            <!-- <view v-if="userInfo.user_type == 2" class="ml-auto">
              <text class="bg-gradient-to-r from-[#ff6b6b] to-[#feca57] text-white px-[20rpx] py-[8rpx] rounded-[20rpx] text-[22rpx] font-bold shadow-lg border border-white border-opacity-30"
                >🏷️ {{ userInfo.merchantType || "商家" }}</text
              >
            </view>
            <view v-else-if="userInfo.user_type == 1" class="ml-auto">
              <text class="bg-gradient-to-r from-[#ff6b6b] to-[#feca57] text-white px-[20rpx] py-[8rpx] rounded-[20rpx] text-[22rpx] font-bold shadow-lg border border-white border-opacity-30"
                >👤 个人</text
              >
            </view>
            <view v-else class="ml-auto">
              <text
                v-if="userInfo.user_type != '3'"
                class="bg-gradient-to-r from-[#ff6b6b] to-[#feca57] text-white px-[20rpx] py-[8rpx] rounded-[20rpx] text-[22rpx] font-bold shadow-lg border border-white border-opacity-30"
              >
                游客
              </text>
            </view> -->
            <view class="ml-auto bg-gradient-to-r from-[#ff6b6b] to-[#feca57] text-white px-[20rpx] py-[8rpx] rounded-[20rpx] text-[22rpx] font-bold shadow-lg border border-white border-opacity-30">{{ getMyType }}</view>
            <view class="ml-auto text-white text-[24rpx] font-bold bg-blue-500/50 px-[20rpx] py-[8rpx] rounded-[20rpx]"
             @click="handleRefundDeposit" v-if="userInfo.user_type == 1 || userInfo.user_type == 2 ">退押金</view>
          </text>
        </view>
      </view>

      <view class="bg-white bg-opacity-15 rounded-[20rpx] p-[25rpx] flex justify-between items-center">
        <view class="text-center" @click="goToIncomeDetail">
          <text class="text-[26rpx] opacity-80 block mb-[10rpx]">平台账户余额</text>
          <text class="text-[40rpx] font-bold">¥ {{ userInfo.balance ? userInfo.balance : "0" }}</text>
        </view>
        <nut-button type="warning" size="small" class="!bg-[#4587cb] px-[40rpx] py-[15rpx] rounded-[50rpx] text-[28rpx] font-bold" @click="handleWithdraw"> 提现到微信 </nut-button>
      </view>
    </view>

    <!-- 实名认证卡片 -->
    <view class="bg-gradient-to-r from-blue-400 to-cyan-400 text-white rounded-[25rpx] p-[30rpx] m-[30rpx] flex items-center justify-between shadow-lg">
      <view class="flex-1">
        <view class="text-[32rpx] font-bold flex items-center">
          <!-- <IconFont name="id-card" class="mr-[16rpx]" /> -->
          <text>{{ userInfo.user_type == 1 ? "个人认证状态:" : userInfo.user_type == 2 ? "商家认证状态:" : "请选择商家或个人认证" }}</text>
          <view class="bg-green-500 px-[15rpx] py-[5rpx] rounded-[15rpx] text-[24rpx] ml-[15rpx]" @tap="jumpRealname(userInfo.real_status, userInfo.user_type)">{{
            userInfo.real_status == 2 ? "已实名" : userInfo.real_status == 1 ? "审核中" : "未实名"
          }}</view>
        </view>
      </view>
      <nut-button type="default" size="small" class="bg-white text-blue-600 px-[40rpx] py-[15rpx] rounded-[50rpx] text-[28rpx] font-bold" @click="handleViewAuth"> 安全设置 </nut-button>
    </view>

    <!-- 实名认证卡片 -->
    <view class="bg-white rounded-[25rpx] p-[30rpx] m-[30rpx] shadow-lg border border-[#E6F4FF]">
      <view class="flex items-center justify-between mb-[20rpx]">
        <view class="flex items-center">
          <view class="w-[60rpx] h-[60rpx] bg-gradient-to-r from-[#165DFF] to-[#4DABF7] rounded-full flex items-center justify-center mr-[20rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="yirenzhengyonghu" size="32" color="#fff" />
          </view>
          <view>
            <text class="text-[32rpx] font-bold text-[#333] block">实名认证</text>
            <text class="text-[24rpx] text-[#666]">保障账户安全</text>
          </view>
        </view>
        <view class="text-right">
          <view
            class="px-[20rpx] py-[8rpx] rounded-full text-[24rpx] font-medium mb-[8rpx]"
            :class="userInfo.real_status == 2 ? 'bg-[#E6F7FF] text-[#165DFF]' : userInfo.real_status == 1 ? 'bg-[#FFF7E6] text-[#FA8C16]' : 'bg-[#FFF2F0] text-[#FF4D4F]'"
          >
            {{ getAuthStatus }}
          </view>
          <nut-button type="primary" size="small" @click="handleAuthPerson">
            {{ userInfo.real_status == 0 ? "立即认证" : "查看详情" }}
          </nut-button>
        </view>
      </view>
    </view>

    <!-- 功能入口卡片 -->
    <view class="bg-white rounded-[25rpx] p-[30rpx] m-[30rpx] shadow-lg">
      <view class="flex justify-between items-center mb-[30rpx] pb-[20rpx] border-b border-gray-100">
        <text class="text-[34rpx] font-bold text-gray-800">我的功能</text>
        <IconFont name="th-large" class="text-blue-500 text-[40rpx]" />
      </view>

      <view class="grid grid-cols-3 gap-[30rpx] max-w-full">
        <view v-for="(item, index) in functionItems" :key="index" class="flex flex-col items-center" @click="handleFunctionClick(item)">
          <view class="w-[90rpx] h-[90rpx] bg-blue-50 rounded-[25rpx] flex items-center justify-center mb-[15rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" :name="item.icon" class="text-blue-500 text-[40rpx]" size="25" />
          </view>
          <text class="text-[26rpx] text-gray-600">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 会员等级卡片 -->
    <view class="bg-white rounded-[25rpx] p-[30rpx] m-[30rpx] shadow-lg">
      <view class="flex justify-between items-center mb-[30rpx] pb-[20rpx] border-b border-gray-100">
        <text class="text-[34rpx] font-bold text-gray-800">会员等级与扣点</text>
        <IconFont name="crown" class="text-blue-500 text-[40rpx]" />
      </view>

      <view class="flex justify-between mb-[30rpx]">
        <view class="bg-gray-50 rounded-[20rpx] p-[30rpx] w-[48%] text-center">
          <text class="text-[32rpx] font-bold mb-[15rpx] block">普通会员</text>
          <text class="text-[48rpx] font-bold text-red-500 mb-[20rpx] block">15%</text>
          <text class="text-[26rpx] text-gray-600">平台信息服务费比例</text>
        </view>

        <view class="bg-gray-50 rounded-[20rpx] p-[30rpx] w-[48%] text-center">
          <text class="text-[32rpx] font-bold mb-[15rpx] block">SVIP会员</text>
          <text class="text-[48rpx] font-bold text-red-500 mb-[20rpx] block">6%</text>
          <text class="text-[26rpx] text-gray-600 mb-[20rpx] block">平台信息服务费比例</text>
          <nut-button type="warning" size="small" class="w-full text-[28rpx] font-bold" @click="handleUpgrade"> 立即升级 </nut-button>
        </view>
      </view>
    </view>

    <!-- 平台商家卡片 -->
    <view class="bg-white rounded-[25rpx] p-[30rpx] m-[30rpx] shadow-lg">
      <view class="flex justify-between items-center mb-[30rpx] pb-[20rpx] border-b border-gray-100">
        <text class="text-[34rpx] font-bold text-gray-800">平台商家服务</text>
        <IconFont name="store" class="text-blue-500 text-[40rpx]" />
      </view>

      <view class="grid grid-cols-4 gap-[30rpx]">
        <view v-for="(item, index) in merchantItems" :key="index" class="flex flex-col items-center" @click="handleMerchantClick(item)">
          <view class="w-[90rpx] h-[90rpx] bg-blue-50 rounded-[25rpx] flex items-center justify-center mb-[15rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" :name="item.icon" class="text-blue-500 text-[40rpx]" size="30" />
          </view>
          <text class="text-[26rpx] text-gray-600 text-center">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 投诉弹窗 -->
    <ComplaintModal v-model:visible="showComplaintModal" />
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import Taro, { useDidShow } from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
import { post, getFullPath } from "@/utils/request";
import { onChangeTab } from "@/utils/hack";
import ren from "@/assets/pic/ren.png";
import ComplaintModal from "@/components/ComplaintModal.vue";
// 导入构建时间
import { BUILD_TIME } from "@/utils/build-time";

// 用户信息
const userStore = useUserStore();
const { userInfo, locationObj } = storeToRefs(userStore);
const publicTime = ref(BUILD_TIME.buildTime);

// 投诉弹窗状态
const showComplaintModal = ref(false);

const getMyType = computed(() => {
  const utype = userInfo.value?.user_type;
  if (!utype) {
    return "游客";
  }
  if (utype == "1") {
    return "个人";
  }
  if (utype == "2") {
    return userInfo.value?.merchantType || "商家";
  }
  if (utype == "3") {
    return "实名认证";
  }
  if (utype == "4") {
    if(userInfo.value?.review_deposit == 0) {
      return "退押金审核中";
    }
    if(userInfo.value?.review_deposit == 1) {
      return "已退押金";
    }
  }
  return "游客";
});

const getAuthStatus = computed(() => {
  if (!userInfo?.value?.real_status) {
    return "未认证";
  }
  // real_status  0 未认证 1 审核中 2 审核通过
  if (userInfo.value.real_status == 2) {
    return "已认证";
  } else if (userInfo.value.real_status == 1) {
    return "审核中";
  } else {
    return "未认证";
  }
});

// 退押金
const handleRefundDeposit = () => {
  Taro.showModal({
    title: "退押金",
    content: "确定要退押金吗？",
    success: (res) => {
      if (res.confirm) {
        post("/my/refundDeposit").then((res) => {
          if (res.code == 0) {
            Taro.showToast({
              title: "退押金成功",
              icon: "success",
            });
            userStore.fetchUserInfo();
          }
          else {
            Taro.showToast({
              title: res.data,
              icon: "none",
            });
          }
        });
      }
    },
  });
};

Taro.useDidShow(() => {
  onChangeTab("mine");
  console.log("userStore.userInfo ===", userStore.userInfo);
  if(userStore.userInfo.id == 7) {
    Taro.navigateTo({
      url: "/pages/webs/register",
    });
    return
  }
  userStore.fetchUserInfo();
  // 获取商户类型数据
  getMerchantTypes();
});

const handleAuthPerson = () => {
  Taro.navigateTo({
    url: "/pages/registration/auth-person?status=" + userInfo.value.real_status,
  });
};

const goinfo = () => {
  Taro.navigateTo({
    // url: "/pages-detail/mine/myinfo",
    url: "/pages/mine/profile",
  });
};

// 功能项目
const functionItems = ref([
  // {
  //   name: "我的任务",
  //   icon: "list-fourliebiao",
  //   url: "/pages/webs/task-details-reward-task-platform",
  // },
  // {
  //   name: "我的订单",
  //   icon: "dingdan",
  //   url: "/pages/webs/order-acceptance-records",
  // },
  // {
  //   name: "我的钱包",
  //   icon: "licai",
  //   url: "/pages/webs/promotion-statistics-center",
  // },
  // {
  //   name: "我的团队",
  //   icon: "tuandui",
  //   url: "/pages/webs/promotion-statistics-center",
  // },
  {
    name: "我的课程",
    icon: "jiaoyupeixunsvg",
    url: "/pages/course/index",
  },
  {
    name: "用户简介",
    icon: "building",
    url: "/pages/mine/profile",
  },
  {
    name: "我的评价",
    icon: "pingjia",
    url: "/pages/webs/credit-level",
  },
  {
    name: "推广中心",
    icon: "tuiguangzhongxin",
    url: "/pages/webs/promotion-statistics-center",
  },
  {
    name: "我的报名",
    icon: "xianxiabaoming",
    url: "pages/registration/my-application",
  },
  {
    name: "我的发布",
    icon: "faburenwu",
    url: "pages/post/my-publish",
  },
  {
    name: "投诉",
    icon: "faburenwu",
    url: "",
  },
]);

// 商家项目 - 从接口获取
const merchantItems = ref<Array<{
  name: string;
  icon: string;
  url: string;
  id?: number;
  deposit?: number;
  vipFree?: number;
  duration?: string;
}>>([]);

// 获取商户类型数据
const getMerchantTypes = async () => {
  try {
    const res = await post("/dictionary/merchantType");
    console.log("获取商户类型数据:", res.data);

    const iconMap = {
      1: 'canyin',
      2: 'peixunguanli', 
      3: 'a-xintuobeifen2',
      4: 'gongyingshang',
      5: 'hezuo',
      6: 'qiyezizhi',
      7: 'a-hezuo3'
    };
    
    merchantItems.value = res.data.map((item: any) => ({
      name: item.columns.name,
      icon: iconMap[item.columns.id], // 使用接口返回的图标，如果没有则使用默认图标
      url: `/pages/webs/merchant-entry?type=${item.columns.id}&status=${userInfo.value.real_status}`,
      id: item.columns.id,
      deposit: item.columns.deposit,
      vipFree: item.columns.membershipFee,
      duration: item.columns.duration
    }));
    
    console.log("处理后的商户类型:", merchantItems.value);
  } catch (error) {
    console.error("获取商户类型失败:", error);
    // 如果接口失败，使用默认数据
    merchantItems.value = [
      {
        name: "服务商",
        icon: "service-provider_fill",
        url: "/pages/webs/merchant-entry?type=1",
      },
      {
        name: "培训商",
        icon: "peixunguanli",
        url: "/pages/webs/merchant-entry?type=2",
      },
      {
        name: "传承商",
        icon: "a-xintuobeifen2",
        url: "/pages/webs/merchant-entry?type=3",
      },
      {
        name: "供应商",
        icon: "chengweishangjia",
        url: "/pages/webs/merchant-entry?type=4",
      },
    ];
  }
};

// 底部导航
const navItems = ref([
  { name: "首页", icon: "home", active: false },
  { name: "任务", icon: "tasks", active: false },
  { name: "我的", icon: "user", active: true },
  { name: "消息", icon: "comments", active: false },
  { name: "更多", icon: "ellipsis-h", active: false },
]);

// 提现
const handleWithdraw = () => {
  // Taro.showToast({
  //   title: '提现申请已提交，将在1-3个工作日内到账',
  //   icon: 'success'
  // })
  Taro.navigateTo({
    url: "/pages/webs/withdraw",
  });
};

// 查看认证详情
const handleViewAuth = () => {
  // Taro.showToast({
  //   title: '实名认证信息：\n姓名：张推广达人\n身份证：450***************\n认证时间：2023-06-15',
  //   icon: 'none'
  // })
  Taro.navigateTo({
    url: "/pages-detail/mine/safe/index",
  });
};

// 升级会员
const handleUpgrade = () => {
  // Taro.showToast({
  //   title: '正在跳转SVIP会员升级页面',
  //   icon: 'none'
  // })
  Taro.navigateTo({
    url: "/pages/webs/member-recharge",
  });
};

// 推广
const handlePromotion = () => {
  Taro.navigateTo({
    url: "/pages/webs/promotion",
  });
};

// 功能点击
const handleFunctionClick = (item: { name: string; url: string }) => {
  // 处理投诉点击
  if (item.name === "投诉") {
    showComplaintModal.value = true;
    return;
  }

  // 其他功能正常跳转
  if (item.url) {
    Taro.navigateTo({
      url: item.url,
    });
  }
};

// 商家点击
const handleMerchantClick = (item: { name: string; url: string }) => {
  // if (item.name == "成为商家") {
  Taro.navigateTo({
    url: item.url,
  });
  // }
};

// 选择地理位置
const handleLocation = () => {
  Taro.navigateTo({
    url: "/pages/webs/location-picker",
  });
};

// 导航点击
const handleNavClick = (name: string) => {
  navItems.value.forEach((item) => {
    item.active = item.name === name;
  });

  Taro.showToast({
    title: `切换到${name}`,
    icon: "none",
  });
};

const handleSetting = () => {
  Taro.removeStorageSync("token");
  Taro.navigateTo({
    url: "pages/webs/register",
  });
};

// 跳转到收入提现明细
const goToIncomeDetail = () => {
  Taro.navigateTo({
    url: "/pages/mine/income-detail",
  });
};

// 根据实名状态跳转
const jumpRealname = (status: number, type: number) => {
  if (status == 0 && type == 0) {
    Taro.showToast({
      title: "您还未进行认证！请选择商家或者个人认证",
    });
    // Taro.navigateTo({
    //   url:'pages/webs/personal-entry'
    // })
  } else if (status == 1 || status == 2) {
    // Taro.showToast({
    //   title:'正在审核中! 请等待'
    // })
    Taro.navigateTo({
      url: type == 1 ? `pages/webs/personal-entry?status=${status}` : `pages/webs/merchant-entry?status=${status}`,
    });
  }
};

// 头像加载失败处理
const handleAvatarError = (event: any) => {
  event.target.src = ren;
};
</script>
